from typing import List

from sqlalchemy import select, delete, and_
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.functions.user import get_user
from app.database.models import Task, User


async def add_task(
    session: AsyncSession,
    task_type: str,
    telegram_id: int,
    link: str,
    count: int,
    interval: int,
    comment_file: str = None,
) -> None:

    user = await get_user(session, telegram_id)

    task = Task(
        user=user,
        type=task_type,
        link=link,
        count_work=count,
        time_interval=interval,
        text=comment_file,
    )

    session.add(task)
    await session.commit()


async def get_user_tasks(session: AsyncSession, user_id: int) -> List[Task]:
    q = select(Task).outerjoin(Task.user).where(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def delete_user_tasks(session: AsyncSession, user_id: int) -> None:

    user = await get_user(session, user_id, joined=True)

    q = delete(Task).where(and_(Task.user == user, Task.status != "busy"))

    await session.execute(q)

    await session.commit()
